import {ElMessage} from "element-plus";

function copyTextIn(content) {
    if (window.clipboardData) {
        window.clipboardData.setData('text', content);
    } else {
        (function (content) {
            document.oncopy = function (e) {
                e.clipboardData.setData('text', content);
                e.preventDefault();
                document.oncopy = null;
            }
        })(content);
        document.execCommand('Copy');
    }
    ElMessage.success('复制 ' + content + '成功。')
}

function subString(strIn, len) {
    let leng = len
    if (strIn && strIn.length > len / 2) {
        for (let i = 0; i < leng; i++) {
            let ch = strIn.charCodeAt(i);
            if (0x007e < ch && ch < 0xff60) {
                // 中文
                leng--
            }
        }
        return strIn.substring(0, leng) + '...'
    }
    return strIn
}

function cloneObj(obj) {
    if (obj === null) {
        return null
    }
    let newObj = {};
    if (obj instanceof Array) {
        newObj = [];
    }
    for (let key in obj) {
        let val = obj[key];
        newObj[key] = typeof val === 'object' ? cloneObj(val) : val;
    }
    return newObj;
}

function isSameDay(date1, date2) {
    return (
        date1.getFullYear() === date2.getFullYear() &&
        date1.getMonth() === date2.getMonth() &&
        date1.getDate() === date2.getDate()
    );
}

function isLoginPage(date1, date2) {
    return !isSameDay(date1, date2) && date2.getTime() - date1.getTime() > 3600_0000;
}


function fileDownload(res) {
    let filename = decodeURIComponent(res.headers.get('filename'))
    let blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'})
    let downloadElement = document.createElement('a')
    // 通过URL.createObjectURL()创建一个url对象
    let href = window.URL.createObjectURL(blob)
    downloadElement.href = href
    // 指定下载文件名
    downloadElement.download = filename
    document.body.appendChild(downloadElement)
    // 点击下载链接
    downloadElement.click()
    // 下载完成后移除下载链接
    document.body.removeChild(downloadElement)
    // 释放资源
    window.URL.revokeObjectURL(href)
}

function addZero(num) {
    if (num < 10) {
        return '0' + num
    } else {
        return num
    }
}

function dataToStr(date) {
    if (typeof date === 'string') {
        date = new Date(date)
    }
    let year = addZero(date.getFullYear());
    let month = addZero(date.getMonth() + 1);
    let day = addZero(date.getDate());
    let hour = addZero(date.getHours());
    let minute = addZero(date.getMinutes());
    let second = addZero(date.getSeconds());

    return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ":" + second
}

export default {
    copyTextIn, subString, cloneObj, isSameDay, isLoginPage, fileDownload, dataToStr
}